local modname = ...
local M={}
_G[modname] = M
package.loaded[modname] = M

local bit=require "bit"

function M.deepcopy(orig)
	local orig_type = type(orig)
	local copy
	if orig_type == 'table' then
		copy = {}
		for orig_key, orig_value in next, orig, nil do
			copy[M.deepcopy(orig_key)] = M.deepcopy(orig_value)
		end
		setmetatable(copy, M.deepcopy(getmetatable(orig)))
	else -- number, string, boolean, etc
		copy = orig
	end
	return copy
end

function M.ipstr_to_ip(str)
	local o1,o2,o3,o4 = string.match(str, "(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)")
	if o1 and o2 and o3 and o4 then
		return 2^24*o1 + 2^16*o2 + 2^8*o3 + o4
	end
	print("ipv4 format: 192.168.1.1")
	os.exit()
end

function M.ip_to_ipstr(ip)
	local n1 = bit.band(bit.rshift(ip, 0),  0x000000FF)
	local n2 = bit.band(bit.rshift(ip, 8),  0x000000FF)
	local n3 = bit.band(bit.rshift(ip, 16), 0x000000FF)
	local n4 = bit.band(bit.rshift(ip, 24), 0x000000FF)

	return string.format("%d.%d.%d.%d", n4, n3, n2, n1)
end

function M.capture(cmd, raw)
	local f = assert(io.popen(cmd .. " 2>/dev/null", 'r'))
	local s = assert(f:read('*a'))
	f:close()
	if raw then return s end
	s = string.gsub(s, '^%s+', '')
	s = string.gsub(s, '%s+$', '')
	s = string.gsub(s, '[\n\r]+', ' ')
	if s == "" then return nil end
	return s
end

